package com.jof.framework.hmc.converter;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.springframework.jms.support.converter.MessageConversionException;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.util.Assert;

import com.jof.framework.hmc.domain.TxtMessage;
import com.thoughtworks.xstream.XStream;

/**
 * this converter is used to transform from @Link {TxtMessage} to @Link
 * {TextMessage}, or vice versa
 * 
 * @author zhangtao
 * 
 */
public class TxtMessageConverter implements MessageConverter {
	private XStream xstream;

	public TxtMessage fromMessage(Message message) throws JMSException,
			MessageConversionException {
		Assert.notNull(xstream, "doesn't allow emtpy xstream");

		xstream.processAnnotations(TxtMessage.class);
		TextMessage textMessage = (TextMessage) message;
		TxtMessage txtMessage = (TxtMessage) xstream
				.fromXML(textMessage.toString());
		return txtMessage;
	}

	public Message toMessage(Object obj, Session session) throws JMSException,
			MessageConversionException {
		Assert.notNull(xstream, "doesn't allow emtpy xstream");
		
		xstream.processAnnotations(TxtMessage.class);
		TextMessage textMessage = session.createTextMessage();
		TxtMessage txtMessage = (TxtMessage) obj;
		textMessage.setText(txtMessage.getText());
		return textMessage;
	}

	public void setXstream(XStream xstream) {
		this.xstream = xstream;
	}
}
